package com.httpapi;

import android.util.Log;

import com.httpapi.apiservice.HttpApiService;
import com.httpapi.apiservice.OnHttpApiListener;

import okhttp3.ResponseBody;

/**
 * 下载服务
 */
public class DownloadServer {


    public void downloadFile(String fileUrl,String fileDir, final int what, final OnHttpApiListener listener){

        retrofit2.Call<ResponseBody> bodyCall = HttpHelper.api().create(HttpApiService.class).downloadFile(fileUrl);
        bodyCall.enqueue(new retrofit2.Callback<ResponseBody>() {
            @Override
            public void onResponse(retrofit2.Call<ResponseBody> call, retrofit2.Response<ResponseBody> response) {
                if (response.isSuccessful()) {
                    Log.d("down","server contacted and has file");
                    int endL=((fileUrl.lastIndexOf(".")>-1)?fileUrl.lastIndexOf("."):fileUrl.length());
                    String fileName = fileUrl.substring(fileUrl.lastIndexOf("/") , endL);
                    FileDownloadRun downloadRun = new FileDownloadRun(what, fileDir,fileName, response, listener);
                    new Thread(downloadRun).start();
                } else {
                    listener.onFailure(what,"server contact failed",0);
//                    LogUtils.d( "server contact failed");
                }
            }

            @Override
            public void onFailure(retrofit2.Call<ResponseBody> call, Throwable t) {
                listener.onFailure(what,"server download failed",0);
//                LogUtils.e( "error");
            }
        });
    }

}
